//
//  CommandLine.m
//  DevSpoof
//
//  Created by huang on 2018/11/5.
//  Copyright © 2018年 wdys. All rights reserved.
//

#import "CommandLine.h"

@implementation CommandLine
+ (instancetype)command:(NSString *)path argvs:(id)argvs{
    CommandLine *line = [CommandLine new];
    line.output = nil;
    return line.pipe(path, argvs);
}
- (CommandLine* (^)(NSString *, id))pipe{
    return ^CommandLine* (NSString *path,id argvs){
        
        NSAssert((argvs == nil) | [argvs isKindOfClass:[NSArray class]] | [argvs isKindOfClass:[NSString class]], nil);
        
        if ([argvs isKindOfClass:[NSString class]]) {
            argvs = @[argvs];
        }
        NSTask *task = [NSTask new];
        task.launchPath = path;
        if (self.output) {
            task.standardInput = self.output;
        }
        task.standardOutput = [NSPipe pipe];
        self.output = task.standardOutput;
        if (argvs) {
            task.arguments = argvs;
        }
        [task launch];
        [task waitUntilExit];
        return self;
    };
}
- (NSString *)read{
    NSData *data = [[self.output fileHandleForReading]availableData];
    return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}
@end
